import Vue from "vue";
/**
 * 校验身份证
 */
export function checkIDCardTools(idCard, msg) {
  // 15位或18位身份证号码的正则表达式
  const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  if (!reg.test(idCard)) {
    Vue.prototype.$showToast({
      show: true,
      text: msg,
      duration: "2000",
    });
    return false;
  }

  // 如果是15位身份证，转换为18位以便计算校验码
  if (idCard.length === 15) {
    const arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    const arrCh = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"];
    let nTemp = 0;
    idCard = idCard.substr(0, 6) + "19" + idCard.substr(6, idCard.length - 6);
    for (let i = 0; i < 17; i++) {
      nTemp += idCard.substr(i, 1) * arrInt[i];
    }
    idCard += arrCh[nTemp % 11];
  }

  // 校验18位身份证的校验码
  if (idCard.length === 18) {
    const arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    const arrCh = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"];
    let nTemp = 0;
    for (let i = 0; i < 17; i++) {
      nTemp += idCard.substr(i, 1) * arrInt[i];
    }
    const valCode = arrCh[nTemp % 11];
    if (valCode !== idCard.substr(17, 1).toUpperCase()) {
      Vue.prototype.$showToast({
        show: true,
        text: msg,
        duration: "2000",
      });
      return false;
    }
  }

  // 验证出生日期
  const birthDate =
    idCard.length === 18
      ? idCard.substring(6, 14)
      : "19" + idCard.substring(6, 12);
  const year = birthDate.substring(0, 4);
  const month = birthDate.substring(4, 6);
  const day = birthDate.substring(6, 8);
  const date = new Date(year, parseInt(month) - 1, parseInt(day));

  if (
    date.getFullYear() !== parseInt(year) ||
    date.getMonth() !== parseInt(month) - 1 ||
    date.getDate() !== parseInt(day)
  ) {
    Vue.prototype.$showToast({
      show: true,
      text: msg,
      duration: "2000",
    });
    return false;
  }
  return true;
}

/**
 * 校验手机号
 */
export function checkPhoneTools(phone, msg) {
  const reg_tel =
    /^1(3[0-9]|4[579]|5[0-3,5-9]|6[2,5-7]|7[0-1,3-8]|8[0-9]|9[0-3,5-9])\d{8}$/;
  const reg_phone = /^(\d{3,4}-)\d{7,8}$/;
  if (!reg_tel.test(phone) && !reg_phone.test(phone)) {
    Vue.prototype.$showToast({
      show: true,
      text: msg,
      duration: "2000",
    });
    return false;
  }
  return true;
}
